package com.dy.yunying.biz.controller.raffle;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.entity.hongbao.HbGiftBag;
import com.dy.yunying.api.entity.raffle.GradeSortReq;
import com.dy.yunying.api.entity.raffle.RaffleActivity;
import com.dy.yunying.api.entity.raffle.RaffleActivityPrize;
import com.dy.yunying.api.enums.GiftTypeEnum;
import com.dy.yunying.api.req.raffle.RaffleActivityPrizeReq;
import com.dy.yunying.biz.service.hongbao.HbGiftBagService;
import com.dy.yunying.biz.service.raffle.RaffleActivityPrizeService;
import com.dy.yunying.biz.service.raffle.RaffleActivityService;
import com.dy.yunying.biz.utils.DateUtils;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 积分商店配置表
 * @author  chengang
 * @version  2022-11-10 10:44:38
 * table: raffle_exchange_store
 */
@RestController
@RequestMapping("/rafflePrize")
@RequiredArgsConstructor
public class RafflePrizeController {
	
    private final RaffleActivityPrizeService raffleActivityPrizeService;
	private final RaffleActivityService raffleActivityService;
	private final HbGiftBagService hbGiftBagService;

	private final String FILE_SUFFIX = "TXT";

	private final Long FILE_MIN_SIZE = 3L;

	private final Long FILE_MAX_SIZE = 1048576L;

	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_PRIZE_LIST')")
	@GetMapping("/list")
	public R getList(Page page, RaffleActivityPrize dto) {
		if (dto.getActivityId() == null || dto.getActivityId() <= 0) {
			return R.failed("活动ID不能为空");
		}
		LambdaQueryWrapper<RaffleActivityPrize> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(RaffleActivityPrize::getDeleted, 0));
		query.and(wrapper -> wrapper.eq(RaffleActivityPrize::getActivityId, dto.getActivityId()));
		query.and(StringUtils.isNotBlank(dto.getPrizeName()),
				wrapper -> wrapper.like(RaffleActivityPrize::getPrizeName,dto.getPrizeName()));

		//根据奖品档位升序
		query.orderByAsc(RaffleActivityPrize::getPrizeGear);
		IPage<RaffleActivityPrize> listPage = raffleActivityPrizeService.page(page, query);
		listPage.getRecords().forEach(a->{
			if(a.getPrizeType() == 2 && a.getGiftType() == 2) {
				a.setGiftAmount(a.getGiftAmount().multiply(new BigDecimal(100)));
			}
		});
		return R.ok(listPage);
	}

	@RequestMapping("/getGradeSort")
	public R getGradeSort(GradeSortReq req){
		if (req.getActivityId() == null || req.getActivityId() <= 0) {
			return R.failed("活动ID不能为空");
		}
		if(StringUtils.isBlank(req.getPrizeGrade())){
			return R.failed("请输入奖品品阶名称");
		}
		return raffleActivityPrizeService.getGradeSort(req);
	}

	/**
	 * 奖品编辑
	 * @return
	 */
	@RequestMapping("/editPrize")
	@PreAuthorize("@pms.hasPermission('RAFFLE_ACTIVITY_EDIT_PRIZE')")
	public R editPrize(RaffleActivityPrizeReq record){
		if (record.getId() == null) {
			return R.failed("未获取到唯一主键ID");
		}
		if (record.getActivityId() == null || record.getActivityId() <= 0) {
			return R.failed("活动ID不能为空");
		}
		RaffleActivity raffleActivity = raffleActivityService.getById(record.getActivityId());
		if(raffleActivity.getActivityStatus()!=1){
			return raffleActivityPrizeService.editOnPrize(record);
		}
		// 验证入参
		R result = checkPrizeParams(record);
		if (CommonConstants.FAIL.equals(result.getCode())) {
			return result;
		}
		return raffleActivityPrizeService.editPrize(record);
	}

	/**
	 * 奖品编辑 - 参数验证
	 * @param record
	 * @return
	 */
	public R checkPrizeParams(RaffleActivityPrizeReq record) {
		// 区服验证
		if (StringUtils.isBlank(record.getPrizeName())) {
			return R.failed("请输入奖品名称");
		}
		record.setPrizeName(record.getPrizeName().trim());
		if (StringUtils.isBlank(record.getPrizeGrade())) {
			return R.failed("请输入奖品品阶名称");
		}
		record.setPrizeGrade(record.getPrizeGrade().trim());
		if (record.getPrizeGradeSort()==null) {
			return R.failed("请输入奖品品阶排序");
		}
		if (record.getPrizeInventory()==null) {
			record.setPrizeInventory(-1);
		}
		if (record.getPrizeWeight()==null) {
			return R.failed("请输入中奖概率");
		}
		if (StringUtils.isBlank(record.getPrizeIconUrl())) {
			return R.failed("请选择奖品icon地址");
		}
		if (record.getPrizeType()==null) {
			return R.failed("请选择奖品类型");
		}
		if(record.getPrizeSingleLimit()==null){
			record.setPrizeSingleLimit(-1);
		}
		if(record.getInfoOpen() == null){
			return R.failed("请选择是否开启详情");
		}
		if(record.getInfoOpen() == 0){
			record.setPrizeInfo(null);
		}
		if(record.getInfoOpen() == 1){
			if (StringUtils.isBlank(record.getPrizeInfo())) {
				return R.failed("请输入奖品详情");
			}
		}

		switch (record.getPrizeType()) {
			case 1:
				record.setPrizeSingleLimit(1);
				if (record.getGiftType() == null) {
					return R.failed("请选择礼包码类型");
				}
				List<HbGiftBag> hbGiftBagList = hbGiftBagService.getBaseMapper().selectList(Wrappers.<HbGiftBag>query().lambda().eq(HbGiftBag::getObjectId,record.getId()).eq(HbGiftBag::getDeleted,0).eq(HbGiftBag::getUsable,1));
				if (CollectionUtils.isEmpty(hbGiftBagList) && GiftTypeEnum.UNIQUE.getType().equals(record.getGiftType())) {
					if (record.getFile() == null || record.getFile().isEmpty()) {
						return R.failed("礼码包、卡密文件不能为空");
					}
					// 获取名称
					String filename = record.getFile().getOriginalFilename();
					// 获取后缀名
					String suffix = filename.substring(filename.lastIndexOf(".") + 1);
					if (!FILE_SUFFIX.equals(suffix.toUpperCase())) {
						return R.failed("礼码包、卡密文件仅支持txt格式");
					}
					Long size = record.getFile().getSize();
					if (size < FILE_MIN_SIZE || size > FILE_MAX_SIZE) {
						return R.failed("礼码包、卡密文件大小应在3字节~1M之间");
					}
				}
				if (GiftTypeEnum.COMMON.getType().equals(record.getGiftType())) {
					if (StringUtils.isBlank(record.getGiftName())) {
						return R.failed("通用码不能为空");
					}
					if (record.getGiftTotalNum() == null) {
						return R.failed("通用礼包码总数量不能为空");
					}
					if (record.getGiftTotalNum() > 999999 || record.getGiftTotalNum() < 0) {
						return R.failed("通用码数量应为1~999999");
					}
				}
				break;
			case 2:
				if (record.getGiftGrantNum() == null) {
					return R.failed("生成数量不能为空");
				}
				if (StringUtils.isBlank(record.getGiftName())) {
					return R.failed("代金券名称不能为空");
				}
				if (record.getGiftAmount() == null) {
					if (record.getGiftType() == 1) {
						return R.failed("代金券金额不能为空");
					}
					if (record.getGiftType() == 2) {
						return R.failed("折扣比例不能为空");
					}
				}
				if (record.getGiftType() == 2) {
					record.setGiftAmount(record.getGiftAmount().divide(new BigDecimal(100)));
				}
				if (record.getGiftUseLimit() == null) {
					return R.failed("满可用金额不能为空");
				}
				if (record.getGiftUseScope() == null) {
					return R.failed("请选择代金券使用限制");
				}
				if (record.getGiftExpireType() == null) {
					return R.failed("请选择有效期规则");
				}
				if (record.getGiftExpireType() == 2) {
					// 时间验证
					if (StringUtils.isBlank(record.getGiftStartTime()) || StringUtils.isBlank(record.getGiftEndTime())) {
						return R.failed("开始时间或结束时间不能为空");
					}
					Date startTime = DateUtils.stringToDate(record.getGiftStartTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
					Date endTime = DateUtils.stringToDate(record.getGiftEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
					if (startTime.getTime() > endTime.getTime()) {
						return R.failed("开始时间不能大于结束时间");
					}
					if (System.currentTimeMillis() > endTime.getTime()) {
						return R.failed("结束时间不能小于当前时间");
					}
				}
				if (record.getGiftExpireType() == 3 && record.getGiftExpireDays() == null) {
					return R.failed("有效天数不能为空");
				}
				break;
			case 3:
				if (record.getGiftAmount() == null) {
					return R.failed("游豆数量不能为空");
				}
				if (record.getGiftType() == 1) {
					record.setGiftExpireType(1);
				}
				if (record.getGiftType() == 2) {
					if (record.getGiftExpireType() == 2) {
						// 时间验证
						if (StringUtils.isBlank(record.getGiftEndTime())) {
							return R.failed("截止时间不能为空");
						}
						Date endTime = DateUtils.stringToDate(record.getGiftEndTime(), DateUtils.YYYY_MM_DD_HH_MM_SS);
						if (System.currentTimeMillis() > endTime.getTime()) {
							return R.failed("结束时间不能小于当前时间");
						}
					}
					if (record.getGiftExpireType() == 3 && record.getGiftExpireDays() == null) {
						return R.failed("有效天数不能为空");
					}
				}
				break;
			case 4:
				if (StringUtils.isBlank(record.getGiftName())) {
					return R.failed("实物名称不能为空");
				}
				record.setGiftName(record.getGiftName().trim());
				break;
			default:
				break;
		}
		return R.ok();
	}
	
}


